//
//  QQLogin.m
//  Pods-Unity-iPhone
//
//  Created by ycgame on 2020/9/29.
//

#import "QQ.h"

#import "OpenSDK_EventManager.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_HttpUtil.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

@interface QQ()<TencentSessionDelegate>

@property(nonatomic, strong)TencentOAuth *tencentOAuth;
@property(nonatomic, assign)BOOL isLogin;
// qq权限
@property(nonatomic, strong)NSArray *permissions;
@end

@implementation QQ

static NSString *APP_CONFIG_QQ=@"QQAppId";

@synthesize loginDelegate;

- (NSString *)getServerName {
    return @"QQ";
}

- (NSString *)getBackgroundImage {
    return @"op_login_type_qq_bg";
}

- (NSString *)getDisplayIcon {
    return @"op_login_type_qq";
}

- (NSString *)getDisplayName {
    return  @"QQ";
}

- (NSString *)getDisplaySdkName {
    return @"QQ账号";
}

- (NSString *)getPlatform {
    return @"QQ";
}

- (NSString *)getPlatformVersion {
    return @"1.0";
}

- (void)startAuth {
    _isLogin = false;
    [self openQQ];
}
 
- (void)startLogin {
    _isLogin = true;
    [self openQQ];
}

- (void)openQQ {
    if ([QQApiInterface isQQInstalled]) {
        _permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, kOPEN_PERMISSION_GET_INFO, nil];
        [_tencentOAuth authorize:_permissions];
    } else {
        if (self.loginDelegate) {
            OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
            [resData fail];
            [resData setErrorMsg:@"抱歉，QQ异常，无法进行QQ登录"];
            [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
            self.loginDelegate(resData);
        }
    }
}

- (void)initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(initSDK:) name:OPENSDK_EVENT_INIT object:nil className:@"QQLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_handleOpenURL:) name:OPENSDK_EVENT_APPLICATION_HANDLEOPENURL object:nil className:@"QQLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_options:) name:OPENSDK_EVENT_APPLICATION_OPENURL_OPTIONS object:nil className:@"QQLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_sourceApplication_annotation:) name:OPENSDK_EVENT_APPLICATION_OPENURL_SOURCEAPPLICATION_ANNOTATION object:nil className:@"QQLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_continue_userActivity:) name:OPENSDK_EVENT_APPLICATION_CONTINUEUSERACTIVITY object:nil className:@"QQLogin"];
}


#pragma mark - OpenSDK初始化时，初始化微信
-(void) initSDK:(NSNotification*) notification {
    // 微信appId
    NSString *appId = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:APP_CONFIG_QQ];
    NSString *universalLinks = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_UNIVERSAL_LINKS];
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appId andUniversalLink:universalLinks andDelegate:self];
}

#pragma mark - 回调需要添加的代码，在系统生命周期回调函数
-(void) application_handleOpenURL:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_handleOpenURL");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [TencentOAuth HandleOpenURL:url];
}

#pragma mark - 回调需要添加的代码，在系统生命周期回调函数
-(void) application_openURL_sourceApplication_annotation:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_openURL_sourceApplication_annotation");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [TencentOAuth HandleOpenURL:url];
}

#pragma mark - universal links 回调
-(void) application_continue_userActivity:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_continue_userActivity");
    NSUserActivity *userActivity = [[notification object] objectForKey:OpenSDK_E_USERACTIVITY];
    [TencentOAuth HandleUniversalLink:userActivity.webpageURL];
}

#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
// NOTE: 9.0以后使用新API接口
-(void) application_openURL_options:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_openURL_options");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [TencentOAuth HandleOpenURL:url];
}

#pragma mark QQLoginDelegate
- (void)tencentDidLogin {
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        // 记录登录用户的OpenID、Token以及过期时间
        if (_isLogin) {
            [OpenSDK_HttpUtil loginWithOtherSDK:@{@"access_token": _tencentOAuth.accessToken,
                                                  @"openid": _tencentOAuth.openId}
                                       platform:[self getPlatform]
                                platformVersion:[self getPlatformVersion]
                                   httpDelegate:self.loginDelegate];
        } else {
            if (self.loginDelegate) {
                OpenSDK_BaseResData *data = [[OpenSDK_BaseResData alloc] init];
                data.status = @"ok";
                data.content = @{@"access_token": _tencentOAuth.accessToken,
                                 @"openid": _tencentOAuth.openId,
                                 @"oauth_type": [self getPlatform],
                                 @"platform_version": [self getPlatformVersion]}.mutableCopy;
                self.loginDelegate(data);
            }
        }
    }
    else
    {
        if (self.loginDelegate) {
            OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
            [resData fail];
            [resData setErrorMsg:@"抱歉，QQ异常，无法进行QQ登录"];
            [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
            self.loginDelegate(resData);
        }
    }
    NSLog(@"qqqqqq: %@", _tencentOAuth.accessToken);
}

- (void)tencentDidNotLogin:(BOOL)cancelled {
    NSLog(@"qqqqqq: %s", cancelled ? "cancel": "nocancel");
    if (cancelled) {
        if (self.loginDelegate) {
            OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
            [resData fail];
            [resData setErrorMsg:@"抱歉，用户取消了QQ登录"];
            [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
            self.loginDelegate(resData);
        }
    } else {
        if (self.loginDelegate) {
            OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
            [resData fail];
            [resData setErrorMsg:@"抱歉，QQ登录失败"];
            [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
            self.loginDelegate(resData);
        }
    }
}


- (void)tencentDidNotNetWork {
    
}
@end
